
/* global View, App, alertify */

(function() {
    
    var groups = {
    
        saving: false,
        collection: null,

        init: function() {
            this.bindGroupList();
            
            this.collection = new Collection();
        },

        bindGroupList: function() {
            var self = this;

            $("#categories").on('click', '.category_name', function() {

                if( $(this).hasClass('editable') || $(this).parents("li").hasClass('selected') ) {
                    return;
                }

                $("#categories li").removeClass("selected");
                $(this).parents("li").addClass('selected');

                var id = $(this).data('id');
                self.loadGroups(id);

            }).on('start-edit.trocar', '.category_name', function() {
                $(this).addClass('editable');
            }).on('end-edit.trocar', '.category_name', function() {
                $(this).removeClass("editable");

                if( $(this).hasClass("category_name") ) {
                    self.saveChanges('category', $.trim($(this).text()), $(this).data('id'));
                }
            });

            $("#groups").on('start-edit.trocar', ".group_name", function() {
                $(this).addClass('editable');
            }).on('end-edit.trocar', ".group_name", function() {
                $(this).removeClass('editable');

                if( $(this).hasClass("group_name") ) {
                    var category_id = $("#categories li.selected .category_name").data('id');
                    var name = $.trim($(this).text());
                    self.saveChanges('group', name, $(this).data('id'), category_id );
                } 
            });

            $(".category_name").trocar({
                on: 'dblclick',
                off: 'blur',
                endOnEnter: true,
                filterPaste: true,
                selectOnEdit: true
            });

            $("#add_category").click(function() {
                self.addCategory();
            });

            $("#add_group").click(function() {
                self.addGroup();
            });

            $("#categories").on('click', ".remove-link", function(e) {
                e.preventDefault();
                e.stopPropagation();
                self.removeCategory( $(this) );
            });

            $("#groups").on('click', ".remove-link", function(e) {
                e.preventDefault();
                e.stopPropagation();
                self.removeGroup( $(this) );
            });
            
            $("#groups").on('click', '.group', function(e) {
                e.preventDefault();
                self.loadGroupDetails( $(this).find('.group_name').data('id') );
            });
            
            $("#group_details").on('click', '#add_leader_btn', function() {
                if( !self['leaderDialog'] ) {
                    self.leaderDialog = new GroupLeaderDialog();
                    self.leaderDialog.registerCallback('leaderAdded', function(data) {
                        $(".group.selected").click();
                    });
                }
                
                $("#add-leader-group-id").val( $("#group_details_form #group-id").val() );
                self.leaderDialog.showDialog();
            });
            
            $("#group_details").on('click', '.remove-leader-btn', function() {
                var leader_item = $(this).parents('.list-group-item');
                var leader_id = leader_item.data('id');
                
                self.removeLeader(leader_id, function() {
                    $(leader_item).slideUp('slow');
                });
            });
        },

        loadGroups: function(category_id) {
            var self = this;
            var url = $("#groups_list").data('url');
            var params = {
                category_id: category_id
            };

            self.showGroupsLoading();

            $.ajax({
                url: url,
                data: params,
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    self.renderGroups(data);
                    self.hideDetailsLoading();
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        },
        
        loadGroupDetails: function(group_id) {
            var self = this;
            var url = App.getBaseURL() + 'settings/group_details';
            var params = {
                action: 'load_group_detail',
                group_id: group_id
            };

            self.showDetailsLoading();

            $.ajax({
                url: url,
                data: params,
                type: 'post',
                success: function(data) {
                    self.renderGroupDetails(data);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        },

        showGroupsLoading: function() {
            $("#groups li").remove();

            var li = $("<li />").html("<i class='fa fa-spinner'></i> Loading .....");
            $("#groups").append(li);
        },
        
        showDetailsLoading: function() {
            $("#group_details #group_details_instruction").hide();
            $("#group_details #group-details-area").html("Loading ...").fadeIn();
        },
        
        hideDetailsLoading: function() {
            $("#group_details #group_details_instruction").show();
            $("#group_details #group-details-area").hide();
        },

        renderGroups: function(data) {

            $("#groups li").remove();

            $(data).each(function(k, v) {
                var gn = $("<div />").addClass("group_name pull-left").html( v.OrganisationGroup.name ).data('id', v.OrganisationGroup.id );
                var rl = $("<a />").attr("href", "#").addClass("remove-link").data("id", v.OrganisationGroup.id).html("<i class='fa fa-trash-o'></i>");
                var opts = $("<div />").addClass("options pull-right").append(rl);
                var li = $("<li />").addClass('group').click(function() {
                    $("#groups li").removeClass("selected");
                    $(this).addClass("selected");
                });

                li.append(gn).append(opts);

                $("#groups").append(li);
            });

            $(".group_name").trocar({
                on: 'dblclick',
                off: 'blur',
                endOnEnter: true,
                filterPaste: true,
                selectOnEdit: true
            });

            $("#add_group").removeAttr("disabled");
        },
        
        renderGroupDetails: function(data) {
            $('#group_details #group-details-area').html(data);
        },

        saveChanges: function(type, name, id, cat_id) {
            var self = this;

            if( self.saving === true ) {
                console.log("saving restricted");
                return;
            }

            self.saving = true;

            var url = $("#save-changes-url").val();
            var params = {
                action: type,
                id: id,
                name: name,
                category_id: cat_id
            };

            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data: params,
                success: function(res) {
                    if( type === 'category' ) {
                        $("#categories .selected .category_name, #categories .selected .remove-link").data('id', res.OrganisationGroupType.id);
                        $("#add_group").removeAttr("disabled");
                    }

                    else if( type === 'group' ) {
                        $("#groups .selected .group_name, #groups .selected .remove-link").data('id', res.OrganisationGroup.id );
                    }

                    self.saving = false;
                },
                error: function(xhr) {
                    console.log(xhr.responseText);

                    self.saving = false;
                }
            });
        },

        addCategory: function() {
            var cn = $("<div />").addClass("category_name pull-left").html("Enter Text Here");
            var opts = $("<div />").addClass("options pull-right").html("<a href='#' class='remove-link'><i class='fa fa-trash-o'></i></a> <i class='fa fa-angle-right'></i>");
            var li = $("<li />").addClass('selected').append(cn, ' ', opts);

            $("#categories").append(li);

            $(cn).trocar({
                on: 'dblclick',
                off: 'blur',
                endOnEnter: true,
                filterPaste: true,
                selectOnEdit: true
            });

            li[0].scrollIntoView(true);
            $(cn).trocar('editable', true);
        },

        addGroup: function() {
            if( $("#categories .selected").length === 0 ) {
                alert('Please Select A Category On The Left First To Add Groups To');
                return;
            }

            var gn = $("<div />").addClass("group_name pull-left").html("Enter Text Here");
            var opts = $("<div />").addClass("options pull-right").html("<a href='#' class='remove-link'><i class='fa fa-trash-o'></i></a>");
            var li = $("<li />").addClass().append(gn, ' ', opts).click(function() {
                $("#groups li").removeClass("selected");
                $(this).addClass("selected");
            });

            $("#groups").append(li);

            $(gn).trocar({
                on: 'dblclick',
                off: 'blur',
                endOnEnter: true,
                filterPaste: true,
                selectOnEdit: true
            });

            li[0].scrollIntoView(true);
            $(gn).trocar('editable', true);
        },

        removeCategory: function(list_item) {
            if( !confirm("Are you sure you want to delete the selected grouping?") ) {
                return;
            }

            $(list_item).parents("li").hide('slow');

            var url = $("#groups_list").data('url');
            var params = {
                action: 'remove_category',
                category_id: $(list_item).data('id')
            };

            $.ajax({
                url: url,
                data: params,
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    $(list_item).parents("li").remove();
                },
                error: function(xhr) {
                    $(list_item).parents("li").show('slow');
                    alert("A server error occured. Please try again or contact support");
                }
            });
        },

        removeGroup: function(list_item) {
            
            confirm("Are you sure you want to delete the selected subgroup?", function() {
                $(list_item).parents("li").hide('slow');

                // item just added so remove immediately from DOM
                if( !$(list_item).data('id') ) {
                    $(list_item).parents("li").remove();
                    return;
                }

                var url = $("#groups_list").data('url');
                var params = {
                    action: 'remove_group',
                    group_id: $(list_item).data('id')
                };

                $.ajax({
                    url: url,
                    data: params,
                    dataType: 'json',
                    type: 'post',
                    success: function(data) {
                        $(list_item).parents("li").slideUp();
                    },
                    error: function(xhr) {
                        $(list_item).parents("li").show('slow');
                        alertify.error("A server error occured. Please try again or contact support");
                    }
                });
            });
        },
        
        removeLeader: function(leader_id, callback) {
            confirm("You are about to remove this leader from this group. Are you sure you want to continue?", function() {
                var url = App.getBaseURL() + "settings/group_details";
                var params = {
                    action: 'remove_group_leader',
                    leader_id: leader_id
                };

                $.ajax({
                    url: url,
                    data: params,
                    dataType: 'json',
                    type: 'post',
                    success: function(data) {
                        if( callback && $.isFunction(callback) ) {
                            callback(data);
                        }
                    },
                    error: function(xhr) {
                        alertify.error("A server error occured. Please try again or contact support");
                    }
                });
            });
        }
    };
    
    var GroupsView = View.extend(groups);
    
    $(document).ready(function() {
        new GroupsView();
    });
})();

var GroupLeaderDialog = (function() {
    
    var dialog = {
    
        init: function() {
            this.setupUI();
        },
        
        showDialog: function() {
            $("#add-leader-image").attr('src', '');
            $("#add-leader-name, #add-leader-role").val('').removeAttr('disabled');
            $("#add-leader-dialog").fadeIn();
            $("#add-leader-name").focus();
        },
        
        hideDialog: function() {
            $("#add-leader-dialog").fadeOut();
        },
        
        setupUI: function() {
            var self = this;
            
            App.UI.memberAutoComplete("#add-leader-name", function(data) {
                $(this).attr('disabled', true);
                $("#add-leader-image").attr('src', data.member_image);
                $("#add-leader-form .add-leader-remove").removeClass('hidden');
                $("#add-leader-id").val( data.organisation_member_id );
                $('#add-leader-role').focus();
            });
            
            $("#add-leader-form .add-leader-remove").click(function() {
                $("#add-leader-name").val('').removeAttr('disabled');
                $("#add-leader-image").attr('src', "");
                $("#add-leader-id").val('');
                
                $(this).addClass('hidden');
            });
            
            $("#add-leader-form").submit(function(e) {
                e.preventDefault();
                
                self.addLeader();
            });
            
            $("#add-leader-form #cancel-btn").click(function(e) {
                e.preventDefault();
                
                self.hideDialog();
            });
        },
        
        addLeader: function() {
            var self = this;
            
            if( $("#add-leader-name").val() == '' ) {
                alertify.error("Please select a member to assign a leadership role");
                $("#add-leader-name").focus();
                return;
            }
            
            if( $("#add-leader-role").val() == '' ) {
                alertify.error("Please enter a role for this leader");
                $("#add-leader-role").focus();
                return;
            }
            
            var url = App.getBaseURL() + "settings/group_details";
            var params = "action=add_group_leader&" + $("#add-leader-form").serialize();
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function( response ) {
                    if( typeof response['status'] != 'undefined' && response.status == 'failed' ) {
                        alertify.error(response.message);
                    }
                    
                    else {
                        self.hideDialog();
                        self.fireCallbacks('leaderAdded', response);
                    }
                },
                error: function( xhr ) {
                    console.log(xhr.responseText);
                }
            });
        }
    };
    
    return View.extend(dialog);
})();



